/**
 * Created with JetBrains WebStorm.
 * User: Brose
 * Date: 2015/5/8
 * Time: 13:49
 */
/**
 *
 * @type {string}
 */
require.config({
    paths: {
        echarts: './media/js/mc/echarts',
        zrender: './media/js/mc/zrender'
    }
});
var taskMap, wordCloud, spss, overper, hv1, hv2;
var _themeName = 'macarons', //主题风格//主题风格
    _backgroundColor = '#fff',
    _tooltip = {},
    _toolbox = { //工具栏
        // show:true,
        orien: 'vertical',
        y: "center",
        feature: {
            restore: {
                show: true
            },
            saveAsImage: {
                show: true
            }
        }
    },
    _calculable = false, //拖拽重计算默认为false
    _symbolSize = 0;
var browserW = getPageViewWidth(); //页面可视宽度
var _rootName = "zb"; //目录名称
var labelTop = {
    normal: {
        label: {
            formatter: function (a) {
                return a.name + "\n" + (a.value * 1).toFixed(2) + '%'
            },
            position: 'center',
            textStyle: {
                fontSize: '14'
            }
        },
        labelLine: {
            show: false
        }
    }
};
var labelBottom = {
    normal: {
        label: {
            show: false
        },
        labelLine: {
            show: false
        }
    },
    emphasis: {}
};
var _srvToolTip = {
    trigger: 'item',
    formatter: "{b}:({d}%)"
};
var _radius = ["50%", "55%"];
var _color = ['#E8EFF0', '#FAD733'];
var _center = ["50%", "90%"];
var _domTaskMap = document.getElementById("zz-task-map"),
    _domWordCloud = document.getElementById("zz-wordcloud"),
    _domSpss = document.getElementById("zz-spss"),
    _domOverPer = document.getElementById("zz-overper"),
    _domHv1 = document.getElementById("zz-hv1"),
    _domHv2 = document.getElementById("zz-hv2");
require(
    [
        'echarts',
        'echarts/chart/pie',
        'echarts/chart/bar',
        'echarts/chart/line',
        'echarts/chart/map',
        'echarts/chart/radar',
        'echarts/chart/scatter',
        'echarts/chart/gauge',
        'echarts/chart/wordCloud'
    ],
    function (ec) {
        init_task_map(ec);
        init_wordCloud(ec);
        init_spss(ec);
        init_overper(ec);
        init_hv1(ec);
        init_hv2(ec);
    }
);


function init_task_map(ec) {
    taskMap = ec.init(_domTaskMap, _themeName);
    //挂载事件库
    var ecConfig = require('echarts/config');
    var option = {};
    $.myAjax(taskMap, './media/geo&map-json/' + _rootName.toUpperCase() + "_map.json", {}, function (data) {
        var i = 0,
            ms = data.resultDatas.seriesData.map1Data;
        while (ms[i]) {
            ms[i].value = myRandom(0, 45);
            i++;
        }
        $.getJSON('./media/geo&map-json/' + _rootName.toUpperCase() + "_geo.json", {}, function (geo) {
            option = {
                backgroundColor: _backgroundColor,
                calculable: _calculable,
                title: {
                    text: data.resultDatas.chartTitle,
                    subtext: data.resultDatas.chartSubTitle
                },
                //tooltip: _tooltip,
                toolbox: _toolbox,
                legend: {
                    orient: 'vertical',
                    x: 'right',
                    data: data.resultDatas.legendData,
                    showLegendSymbol: true
                },
                calculable: false,
                dataRange: {
                    show: false,
                    min: 0,
                    max: 50,
                    itemWidth: 15,
                    itemHeight: 15,
                    color: ['#2F8CE4', '#DFFEFE'],
                    orient: 'vertical',
                    itemGap: 0,
                    y: 'bottom',
                    x: 30
                },
                series: [{
                    mapLocation: {
                        x: 100,
                        height: 390
                    },
                    name: '安全态势',
                    type: 'map',
                    mapType: 'china',
                    selectedMode: 'single',
                    itemStyle: {
                        normal: {
                            borderWidth: 1,
                            borderColor: "#999",
                            label: {
                                show: true,
                                textStyle: {
                                    color: "#000"
                                }
                            }
                        },
                        emphasis: {
                            label: {
                                show: true,
                                textStyle: {
                                    color: "#fff"
                                }
                            }
                        }
                    },
                    data: ms,
                    geoCoord: geo
                }, {
                    name: '七大军区',
                    type: 'map',
                    mapType: 'china',
                    data: [],
                    itemStyle: {
                        normal: {
                            label: {
                                show: false
                            },
                            borderWidth: 2,
                            lineStyle: {
                                type: 'dashed',
                                color: "yellow",
                                shadowBlur: 10
                            }
                        }
                    },
                    /*
                     markLine: {
                     smooth: true,
                     effect: {
                     show: true,
                     scaleSize: 1,
                     period: 30,
                     color: '#fff',
                     shadowBlur: 10
                     },
                     itemStyle: {
                     normal: {
                     label: {
                     show: false
                     },
                     borderWidth: 2,
                     lineStyle: {
                     type: 'dashed',
                     color: "yellow",
                     shadowBlur: 10
                     }
                     }
                     },
                     data: [
                     [{
                     name: '成都军区'
                     }, {
                     name: '北京军区'
                     }

                     ],
                     [{
                     name: '沈阳军区'
                     }, {
                     name: '北京军区'
                     }

                     ],
                     [{
                     name: '南京军区'
                     }, {
                     name: '北京军区'
                     }

                     ],
                     [{
                     name: '兰州军区'
                     }, {
                     name: '北京军区'
                     }

                     ],
                     [{
                     name: '广州军区'
                     }, {
                     name: '北京军区'
                     }

                     ],
                     [{
                     name: '济南军区'
                     }, {
                     name: '北京军区'
                     }

                     ]
                     ]
                     },*/
                    markPoint: {
                        symbol: 'emptyCircle',
                        symbolSize: function (v) {
                            return 10 + v / 100
                        },
                        effect: {
                            show: true,
                            shadowBlur: 0
                        },
                        itemStyle: {
                            normal: {
                                color: function (d) {
                                    return d.data.value > 0 ? "red" : "green";
                                },
                                label: {
                                    show: false
                                },
                                lineStyle: {
                                    type: 'dashed',
                                    color: "yellow",
                                    shadowBlur: 10
                                }
                            },
                            emphasis: {
                                label: {
                                    show: false
                                }
                            }
                        },
                        data: data.resultDatas.seriesData.map2Data
                    }
                }]
            };
            taskMap._mySetOption(option);
            //鼠标事件扩展:跳转到军区
            taskMap.on(ecConfig.EVENT.CLICK, function (e) {
                if (e.seriesIndex == 1) { // 七大军区地图索引为1
                    if (e.name === "沈阳军区") {
                        location.href = "shenyang.html";
                    } else if (e.name === "成都军区") {
                        location.href = "chengdu.html";
                    }
                }
            });
            //鼠标事件扩展:只提示军区数值
            taskMap.on(ecConfig.EVENT.HOVER, function (e) {
                var _mouPos = getMousePos(e.event);
                var _html = "<span>" + e.name + ":</span>&nbsp;<span style='color:#fff'>" + e.value + "</span>&nbsp;"
                if (e.seriesIndex == 1) { // 七大军区索引为1
                    //获取鼠标位置
                    MyTip.show(document, _mouPos, _html)
                }
            });
            taskMap.on(ecConfig.EVENT.MOUSEOUT, function (e) {
                if (e.seriesIndex == 1) {
                    MyTip.hide();
                }
            });
        })
    });

}
function init_wordCloud(ec) {
    wordCloud = ec.init(_domWordCloud, _themeName);

    $("#zz-wordcloud").children().remove();
    var _errorDiv = $("<div>").addClass("mc-chart-error").html("<span>努力的读取数据中...</span>");
    _errorDiv.appendTo($("#zz-wordcloud"));
    var _cloudDivWidth = $("#zz-wordcloud").width(), _cloudDivHeight = $("#zz-wordcloud").height();
    var _size = [_cloudDivWidth, _cloudDivHeight];//设置大小
    var _requests=["./media/local-json-"+_rootName+"/rzx_wordcloud.json",jsonUrl + "RZX/RZXKeyWord"];
    $.ajax({
        url: _requests[_REQUEST_TYPE],
        data: {},
        dataType: _requests[_REQUEST_TYPE].indexOf(".json")>-1?"json":"jsonp",
        jsonp: "callback",
        timeout: 10000,
        success: function (cbd) {
            cbd=cbd.result?cbd.result:cbd;
            $("#zz-wordcloud .mc-chart-error").hide();
            var fill = d3.scale.category20();
            var layout = d3.layout.cloud()
                .size(_size)
                .words((function () {
                    var _hotWords = [];
                    var _ajaxResultData = cbd.resultDatas.seriesData.wordsData;
                    if (_ajaxResultData.length < 1) {
                        $("#zz-wordcloud .mc-chart-error").show();
                        $("#zz-wordcloud .mc-chart-error").html("<span>暂无数据</span>");
                        return [];
                    }
                    for (var i = 0; i < _ajaxResultData.length; i++) {
                        _hotWords.push(_ajaxResultData[i].hotword + "-" + _ajaxResultData[i].num)
                    }
                    return _hotWords;
                })().map(function (d) {
                    return {text: d, size: 14 + Math.random() * 14, test: "haha"};
                }))
                .padding(0)
                .rotate(function () {
                    return ~~(Math.random() * 2) * 90;
                })
                .font("Impact")
                .fontSize(function (d) {
                    return d.size;
                })
                .on("end", draw).start();

            function draw(words) {

                //费老劲了，给words的text属性值重新定义，并且添加属性cv,目的在于将这个热词的value带进来使用
                for (var i = 0; i < words.length; i++) {
                    var _text = words[i].text.split("-")[0],
                        _cv = words[i].text.split("-")[1];
                    words[i].text = _text
                    words[i].cv = _cv;
                }
                var _svg = d3.select("#zz-wordcloud").append("svg")
                    .attr("width", _size[0])
                    .attr("height", _size[1])
                    .append("g")
                    .attr("transform", "translate(" + _size[0] / 2 + "," + _size[1] / 2 + ")")
                    .selectAll("text")
                    .data(words)
                    .enter().append("text")
                    .style("font-size", function (d) {
                        return d.size + "px";
                    })
                    .style("z-index", function (d) {
                        return d.cv;
                    })  //将cv值存在一个无关紧要的css属性中，这里我选择的是z-index
                    .style("font-family", "Arial, 'Microsoft Yahei'")
                    .style("cursor", "pointer")
                    .style("fill", function (d, i) {
                        return fill(i);
                    })
                    .attr("text-anchor", "middle")
                    .attr("transform", function (d) {
                        return "translate(" + [d.x, d.y] + ")rotate(" + (d.rotate+2) + ")";
                    })
                    .text(function (d) {
                        return d.text;
                    });

            }

        }, error: function (er) {
            $("#zz-wordcloud .mc-chart-error").show();
            $("#zz-wordcloud .mc-chart-error").html("<span>数据请求超时</span>");
        }
    })
}
function init_spss(ec) {
    spss = ec.init(_domSpss, _themeName);
    var _requests = ["./media/src.json", jsonUrl + "sysInfo/cpu"]
    $.myAjax(spss, _requests[_REQUEST_TYPE], {}, function (data) {
        var option = {
            backgroundColor: _backgroundColor,
            color: ['#27C24C','#E55853','#FBAD40','#E8EFF0'],
            legend:{
                orient:"vertical",
                x:"right",
                y:5,
                data:["正面","负面","中立","未知"]
            },
            center: _center,
            tooltip: _srvToolTip,
            calculable: false,
            series: [{
                name: '倾向性分析',
                type: 'pie',
                radius: _radius,

                data: [{
                    value: 19,
                    name: '正面',
                    itemStyle: labelTop
                }, {
                    value:35,
                    name: '负面',
                  itemStyle: labelBottom
                }, {
                    value: 43,
                    name: '中立',
                    itemStyle: labelBottom
                }, {
                    value: 1,
                    name: '未知',
                    itemStyle: labelBottom
                }
                ]
            }]
        };
        spss._mySetOption(option);
        spss.refresh();
    });
}
function init_overper(ec) {
    overper = ec.init(_domOverPer, _themeName);
    var _requests = ["./media/src.json", jsonUrl + "sysInfo/cpu"]
    $.myAjax(overper, _requests[_REQUEST_TYPE], {}, function (data) {
        var option = {
            backgroundColor: _backgroundColor,
            color: ['#E8EFF0', '#23B7E5'],
            center: _center,
            tooltip: _srvToolTip,
            calculable: false,
            series: [{
                name: '完成率',
                type: 'pie',
                radius: _radius,

                data: [{
                    value: (100 - data.resultDatas.seriesData.src_use),
                    name: '未完成',
                    itemStyle: labelBottom
                }, {
                    value: data.resultDatas.seriesData.src_use,
                    name: '完成率',
                    itemStyle: labelTop
                }
                ]
            }]
        };
        overper._mySetOption(option);
        overper.refresh();
    });
}
function init_hv1(ec) {
    hv1 = ec.init(_domHv1, _themeName);
    var psDatas = function () {
        var _rs = [];
        for (var i = 0; i < 7; i++) {
            _rs.push(myRandom(20, 45));
        }
        return _rs;
    };
    var _itemStyle = {
        normal: {
            barBorderRadius: 0
        },
        emphasis: {
            barBorderRadius: 0
        }
    }
    var option = {
        backgroundColor: _backgroundColor,
        color: ["#8BD9F1", "#8ADE9E", "#B2ACD9", "#F6F8F8"],
        title: {
            show: false
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            data: ['新闻', '微博', '论坛', '博客'],
            x: "right",
            y: 0
        },
        toolbox: _toolbox,
        calculable: false,
        grid: {x: 25, y: 25, x2: 10, y2: 25},
        xAxis: [
            {
                type: 'category',
                data: ['Aug 17', 'Aug 18', 'Aug 19', 'Aug 20', 'Aug 21', 'Aug 22', 'Aug 23'],
                axisLabel: {
                    textStyle: {
                        color: '#999'
                    }
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    textStyle: {
                        color: '#999'
                    }
                }
            }
        ],
        series: [
            {
                name: '新闻',
                type: 'bar',
                data: psDatas(),
                barGap:0,
                itemStyle: {
                    normal: {
                        barBorderWidth:1,
                        barBorderColor:"#43C2E9",
                        barBorderRadius: 0
                    },
                    emphasis: {
                        barBorderRadius: 0
                    }
                }
            },
            {
                name: '微博',
                type: 'bar',
                data: psDatas(),
                barGap:0,
                itemStyle: {
                    normal: {
                        barBorderWidth:1,
                        barBorderColor:"#54CF6D",
                        barBorderRadius: 0
                    },
                    emphasis: {
                        barBorderRadius: 0
                    }
                }
            },
            {
                name: '论坛',
                type: 'bar',
                barGap:0,
                data: psDatas(),
                itemStyle: {
                    normal: {
                        barBorderWidth:1,
                        barBorderColor:"#9B8BD2",
                        barBorderRadius: 0
                    },
                    emphasis: {
                        barBorderRadius: 0
                    }
                }
            },
            {
                name: '博客',
                type: 'bar',
                barGap:0,
                data: psDatas(),
                itemStyle: {
                    normal: {
                        barBorderWidth:1,
                        barBorderColor:"#E1E7E9",
                        barBorderRadius: 0
                    },
                    emphasis: {
                        barBorderRadius: 0
                    }
                }
            }
        ]
    };
    hv1.setOption(option);
}
function init_hv2(ec) {
    hv2 = ec.init(_domHv2, _themeName);
    var psDatas = function randData() {
        var _rs = [];
        for (var i = 0; i < 30; i++) {
            _rs.push(myRandom(200, 350));
        }
        return _rs;
    };
    var _requests = ["./media/local-json-" + _rootName + "/line.json", "./media/local-json-" + _rootName + "/line.json"];
    $.myAjax(hv2, _requests[_REQUEST_TYPE], {}, function (data) {
        var option = {
            backgroundColor: _backgroundColor,
            color: ["#60CBEC", "#78D98F", "#988FCC", "#999"],
            calculable: false,
            title: {
                show: false
            },
            tooltip: _tooltip,
            legend: {
                orient: 'horizontal',
                x: "right",
                y: 0,
                data: ['新闻', '微博', '论坛', '博客']
            },
            grid: {x: 10, y: 25, x2: 10, y2: 25},
            toolbox: _toolbox,
            calculable: false,
            xAxis: [{
                type: 'category',
                data: (function () {
                    var _nd = DateFormat("yyyy-MM-dd", new Date()), _rs = [];  //获取今天日期  yyyy-MM-dd
                    var _nds = _nd.split("-"), _m = _nds[1] * 1, _tm = _m;
                    _n = _nds[2] * 1;
                    var d, c = 30;
                    for (var i = _nds[2]; i >= (_nds[2] - 6); i--) {
                        d = i;
                        if (d <= 0) {
                            d = c--;  //模拟上个月是31天，从月底30号向前推的情况
                            _m = (_tm - 1) ? "0" + (_tm - 1) : _tm - 1;
                        } else {
                            _m = _tm ? "0" + _tm : _tm;
                        }
                        d = Math.abs(d);
                        _rs.push(_m + "-" + d);
                    }
                    return _rs;
                })(),
                axisLabel: {
                    textStyle: {
                        color: '#999'
                    }
                }
            }],
            yAxis: [{
                type: 'value',
                show: false,
                min:0,
                max:500
            }],
            series: [{
                name: "新闻",
                type: "line",
                symbolSize: _symbolSize,
                smooth: false,
                data: psDatas()
            }, {
                name: "微博",
                type: "line",
                symbolSize: _symbolSize,
                smooth: false,
                data: psDatas()
            }, {
                name: "论坛",
                type: "line",
                symbolSize: _symbolSize,
                smooth: false,
                data: psDatas()
            }, {
                name: "博客",
                type: "line",
                symbolSize: _symbolSize,
                smooth: false,
                data: psDatas()
            }
            ]
        };
        hv2._mySetOption(option);
    });
}
